package net.lastcoder.ifserver.packet;

import net.lastcoder.ifserver.Constants;
import net.lastcoder.ifserver.util.DataTypeUtil;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * auth: WenYF
 * date: 2016/9/29
 * @deprecated 请使用Event
 */
public class Message extends Packet {

    private String title = new String(new byte[0]);
    private String body = "";
    /**
     * @param title 不能为null
     */
    public Message(String title) {
        this.title = title;
    }

    /**
     * @param title 不能为null
     */
    public Message(byte[] title) {
        this.title = new String(title, charset);
    }

    public String getTitle() {
        return title;
    }

    /**
     * @param title 不能为null
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @param title 不能为null
     */
    public void setTitle(byte[] title) {
        this.title = new String(title, charset);
    }

    public String getBody() {
        return body == null ? "" : body;
    }

    public byte[] getRawBody() {
        return body.getBytes(charset);
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setBody(byte[] body) {
        this.body = new String(body, charset);
    }

    @Override
    protected byte[] getContent(boolean isBinary) {
        if (isBinary) {
            return getBinary();
        } else {
            return getJson();
        }
    }

    private byte[] getJson(){
        JSONObject json = new JSONObject();
        try {
            json.put("title", title);
            json.put("body", getBody());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json.toString().getBytes();
    }

    private byte[] getBinary() {
        byte[] titleBytes = title.getBytes();
        byte[] bodyBytes= getRawBody();

        byte[] content = new byte[1 + titleBytes.length + 4 + bodyBytes.length];
        content[0] = (byte) titleBytes.length;
        int count = 1, i;
        for (i = 0; i < titleBytes.length && count < content.length; i ++, count ++) {
            content[count] = titleBytes[i];
        }
        byte[] lengthBytes = DataTypeUtil.intToByteArray(bodyBytes.length);
        for (i = 0; i < lengthBytes.length && count < content.length; i ++, count ++) {
            content[count] = lengthBytes[i];
        }
        for (i = 0; i < bodyBytes.length && count < content.length; i ++, count ++) {
            content[count] = bodyBytes[i];
        }
        return content;
    }

    @Override
    public byte getPacketType() {
        return Constants.PACKET_TYPE_MESSAGE;
    }

    @Override
    public String toString() {
        return super.toString() + " Message{" +
                "title='" + getTitle() + '\'' +
                ", body='" + getBody() + '\'' +
                '}';
    }
}
